package com.money.consumption;


import com.common.rabitmq.RabbitmqName;
import com.money.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.ConcurrentSkipListMap;


/**
 *     订单处理
 */
@Component
@Slf4j
public class OrderConsumption {
    @Autowired
    private OrderService orderService;

    private ConcurrentSkipListMap<Long, String> map = new ConcurrentSkipListMap<>();

    @RabbitListener(queues = {RabbitmqName.RAPID_ORDER})
    public void queueRead(Message message, Channel channel) {
        //获取到我们的订单id
        String orderId = new String(message.getBody());
        // System.out.println(orderId);
        //  System.out.println("当前接收时间："+new SimpleDateFormat("HH:mm:ss").format(new Date()));
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            //开启手动确认模式
            channel.confirmSelect();
            //业务代码
            orderService.queryStatus(orderId);
            //没有异常就确认
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            //消费失败重新放入到我们的队列中去
            try {
                channel.basicNack(deliveryTag, false, true);
            } catch (IOException ioException) {
                //这个地方我们可以把重新放入队列失败的任务保存 数据库或者是redis当中去  防止我们的 任务丢失
                log.error("重新放入队列失败，失败原因：{}", e.getMessage(), e);
            }
            //拒绝消息,为true会重新放回队列（自定义拒绝规则，比如：redis计数，消费5次后依然报错失败则拒绝）
            //channel.basicReject(deliverTag, false);
        }
    }
}
